<?php
/**
 * webboard.php
 * Webboard management
 * @category classes
 *
 * @author AonzZung
 * @copyright AonzZung
 * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
 * @version 0.1
 *
 * @see required files
 * TPL
 * - webboard.tpl
 * - webboard-pagination.tpl
 * - webboard-topic.tpl
 * - webboard-new-topic.tpl
 * 
 * Page Processing
 * - webboard.php
 * 
 * Model 
 * - Webboard.php
 * 
 * Jquery
 * - mark it up editor (markitup.jaysalvat.com) (js/jquery/markitupeditor)
 * 
 * Tools
 * - php captcha (www.phpcaptcha.org) (\tools\phpcaptcha)
 * 
 * DB
 * - webboard
 */


/* SSL Management */
//$useSSL = true;
session_start();

include(dirname(__FILE__).'/config/config.inc.php');
/*BB2HTML Parser*/
include(dirname(__FILE__).'/js/jquery/markitupeditor/markitup/parsers/markitup.bbcode-parser.php');

include(dirname(__FILE__).'/init.php');

include(dirname(__FILE__).'/header.php');
/* errors */
$errors = array();

/* Constants */
define("POST_ACTION_BOARD", "BOARD");
define("POST_ACTION_TOPIC", "TOPIC");
define("TOPIC_COUNT_PER_PAGE", 10); //the number of topics per page. 
define("REGEX_BOARD_TOPIC", "/^\d*\.{1}\d+$/i");
//define("SHOW_ADMIN_PANEL", $cookie->isLogged() && Employee::employeeExists($cookie->email) ); 

//Admin users who can edit webboard
//1. id = 2 -> bug_aonz
$admin_user = intval($cookie->id_customer) == 2 ? true : false;

$action = Tools::getValue('action',NULL);// "post"
$board = Tools::getValue('board',NULL);
$topic = Tools::getValue('topic',NULL);

/* Post mode*/
$post_mode = Tools::getValue('post_mode',NULL);
/* Back after post */
$back = Tools::getValue('back',NULL);
if (!is_null($back))
{
	$smarty->assign('back', $back);
}
else
{
	$smarty->assign('back', "webboard.php?board=0.1");
}

//=== Page processing ===
if( !empty($board) && empty($action))
{
	if( validateBoardAndTopicAttributes($board) )
	{
		//Display webboard
		displayBoard($board);
	}
}
else if( !empty($topic) && empty($action) )
{
	if( validateBoardAndTopicAttributes($topic) )
	{
		//Display topic
		displayTopic($topic);
	}
}
else if( $action=='post' && ( !empty($board)  || !empty($topic) ) )
{
	$param = "";
	$post_action = "";
	if(!empty($board))
	{
		if( validateBoardAndTopicAttributes($board) )
		{
			$param = $board;
			$post_action = POST_ACTION_BOARD;
		}
	}
	else if (!empty($topic))
	{
		if( validateBoardAndTopicAttributes($topic) )
		{
			$param= $topic;
			$post_action = POST_ACTION_TOPIC;
		}
	}
	else
	{
		$errors[] = Tools::displayError('Unable to post a new topic.');
		$smarty->assign('errors', $errors);
		displayBoard();
	}
	//Post a new topic
	if( empty($errors))
	{
		displayPostCreator($param,$post_action );
	}
}
else if ($action == 'submit_post')
{
	include_once _PS_TOOL_DIR_. '/phpcaptcha/securimage.php';

	$securimage = new Securimage();
	if ($securimage->check($_POST['captcha_code']) == false) 
	{
		// the code was incorrect
		// handle the error accordingly with your other error checking
		$errors[] = Tools::displayError('The Validation Code was incorrect, please try again.');
		
		// or you can do something really basic like this
		$smarty->assign('errors', $errors);
		displayPostCreator(Tools::getValue('topic_id',NULL).'.1',Tools::getValue('post_action',NULL) );
	}
	else
	{
		doPost( Tools::getValue('post_action',NULL),
				Tools::getValue('topic_id',NULL),
				Tools::getValue('topic_title',NULL),
				Tools::getValue('topic_content',NULL),
				Tools::getValue('author',NULL),
				$cookie->id_customer);
	}
}
else if ($action == 'pin' || $action == 'unpin')
{
	if( $admin_user )
	{
		$topic_id = Tools::getValue('topic_id',NULL);	
		$success = false;
		if( !is_null($topic_id) )
		{
		   	$success = Webboard::pinTopic( $topic_id , $action);
		}
		if( is_null($topic_id) || !$success )
		{
			if( $action=='pin' )
				$errors[] = Tools::displayError('Unable to pin topic.');
			if( $action=='unpin' )	
				$errors[] = Tools::displayError('Unable to unpin topic.');
			$smarty->assign('errors', $errors);
			displayBoard("0.1");
		}
		else
		{
			displayBoard("0.1");
		}
	}	
	else
	{
		displayBoard("0.1");
	}
}
else if ($action == 'delete')
{
	if( $admin_user )
	{
		$topic_id = Tools::getValue('topic_id',NULL);
		$success = false;
		if( !is_null($topic_id) )
		{
			$success = Webboard::deleteTopic( $topic_id );
		}
		if( is_null($topic_id) || !$success )
		{
			$errors[] = Tools::displayError('Unable to delete topic.');
			$smarty->assign('errors', $errors);
			displayBoard("0.1");
		}
		else
		{
			displayBoard("0.1");
		}
	}
	else
	{
		displayBoard("0.1");
	}
}
else
{
	displayBoard("0.1");
}

/*===== Functions =====*/
/**
 * get Board Or Topic ID
 * @return id number of board or topic.
 */
function getBoardOrTopicID( $dotDelimitedValue )
{
	$arr = explode( ".", $dotDelimitedValue);
	if(count($arr) != 2)
	{
		return null;
	}
	return intval($arr[0]);
}
function getSelectedPage($dotDelimitedValue)
{
	$arr = explode( '.', $dotDelimitedValue);
	if(count($arr) != 2)
	{
		return null;
	}
	return intval($arr[1]);
}
function displayBoard( $board="0.1" )
{
	global $smarty,$admin_user,$errors;
	$selectedPage = getSelectedPage($board);
	initPagination( POST_ACTION_BOARD, intval(getBoardOrTopicID($board)), intval($selectedPage));
	$topics = Webboard::getTopics( $selectedPage, TOPIC_COUNT_PER_PAGE);
	if(count($topics) > 0)
	{		
		$smarty->assign(array(
		'topics' => array_map( 'showAdminIcon', array_map('countViews', $topics)),
		'selectedPage' => $selectedPage,
		'adminUser' => $admin_user
		));
	
		$smarty->display(_PS_THEME_DIR_.'webboard.tpl');
	}
	else
	{
		//TODO: Note! No any topics will cause infinite loop errors.
		$errors[] = Tools::displayError('The board you entered doesn\'t exist' );
		$smarty->assign('errors', $errors);
		displayBoard();
	}
}
function displayTopic( $topic="0.1" )
{
	global $smarty,$admin_user,$errors;
	$topic_id = getBoardOrTopicID($topic);
	$selectedPage = getSelectedPage($topic);
	Webboard::countView($topic_id, $_SERVER['REMOTE_ADDR']);
	initPagination( POST_ACTION_TOPIC, intval($topic_id), intval($selectedPage));
	$topic = Webboard::getTopic( $topic_id );
	$replies = Webboard::getReplies( $topic_id,$selectedPage, TOPIC_COUNT_PER_PAGE );
	if(count($topic) == 1 && 
		(($selectedPage == 1 && count($replies) >= 0) || ($selectedPage > 1 && count($replies) > 0))
	   )
	{
		$smarty->assign(array(
			'topic' => array_map( 'showAdminIcon', array_map('convertBBcode2HtmlContent', $topic )),
			'replies' => array_map( 'showAdminIcon', array_map('convertBBcode2HtmlContent', $replies)),
			'adminUser' => $admin_user
		));
		$smarty->display(_PS_THEME_DIR_.'webboard-topic.tpl');
	}
	else
	{
		$errors[] = Tools::displayError('The board you entered doesn\'t exist' );
		$smarty->assign('errors', $errors);
		displayBoard();
	}
}

function displayPostCreator( $topic, $post_action )
{
	global $smarty;
	$topic_id = getBoardOrTopicID($topic);

	$smarty->assign(array(
		'post_action' => $post_action, //BOARD or TOPIC
		'topic_id' => intval($topic_id),
		'topic_title' => Webboard::getTopicTitle($topic_id),
		'back' => Tools::safeOutput('webboard.php?'.strtolower($post_action).'='.$topic_id.'.1')
	));
	$smarty->display(_PS_THEME_DIR_.'webboard-new-topic.tpl');

}

//Convert topic content of webboard array to HTML
function convertBBcode2HtmlContent( $webboard_array )
{
	if ( is_array($webboard_array) && array_key_exists('topic_content', $webboard_array)) 
	{
		$webboard_array['topic_content'] = Tools::htmlentitiesDecodeUTF8( BBCode2Html(trim($webboard_array['topic_content'])) );
		return $webboard_array;
	}
	return null;
}

function showAdminIcon( $webboard_array )
{
	if ( is_array($webboard_array) && array_key_exists('email', $webboard_array)) 
	{
		$email = $webboard_array['email'];
		
		if(!Employee::employeeExists($email))
		{
			$webboard_array['show_admin_icon'] = false;
		}
		else
		{
			$webboard_array['show_admin_icon'] = true;
		}
		return $webboard_array;
	}
	return null;
}

function countViews($webboard_array)
{
	if ( is_array($webboard_array) && array_key_exists('views', $webboard_array)) 
	{
		$ip_arr = explode(',',$webboard_array['views']);
		$webboard_array['views'] = count($ip_arr);
		return $webboard_array;
	}
	return null;
}
function doPost($post_action, $topic_id, $topic_title, $topic_content,$author, $author_id )
{
	global $smarty,$back,$errors;
	$maxContentLength = 1000;
	
	$webboardObj = new Webboard();
	switch($post_action)
	{
		case POST_ACTION_BOARD:
			if( is_null($topic_title) || trim($topic_title)=='')
			{
				$errors[] = Tools::displayError('Topic cannot be empty.');
				break;
			}
			else if(strlen(trim($topic_title)) > 100)
			{
				$errors[] = Tools::displayError('Topic must be less than or equal 100 charactors.');
				break;
			}
			$webboardObj->topic_title = trim($topic_title);
			$webboardObj->mode = POST_ACTION_BOARD;
			break;
		case POST_ACTION_TOPIC:
			if( is_null($topic_id) )
			{
				$errors[] = Tools::displayError('Have some problems. Unable to post.');
				break;
			}
			else if( !Webboard::checkTopicIdExist($topic_id))
			{
				$errors[] = Tools::displayError('Topic you select is not exist.');
				break;
			}
			$webboardObj->parent_topic_id = intval($topic_id);
			$webboardObj->mode = POST_ACTION_TOPIC;
			break;
	}
	//Check empty content
	if( is_null($topic_content) || trim($topic_content)=='' )
	{
		$errors[] = Tools::displayError('Message cannot be empty.');
	}
	else
	{
		if( strlen( trim($topic_content) ) > $maxContentLength )
		{
			$topic_content = substr(trim($topic_content),0,$maxContentLength) ;
		}
		$webboardObj->topic_content = trim($topic_content);
	}
	
	//Check author id
	if( is_null($author_id)|| empty($author_id) )
	{
		//Guest user
		$webboardObj->author_id = 0; //For guest
		//Check author name
		if( is_null($author)|| empty($author) )
		{
			$errors[] = Tools::displayError('Name cannot be empty.');
		}
		else
		{
			$webboardObj->author = trim($author);
		}
	}
	else
	{
		//Logged-in user
		$webboardObj->author_id = intval(trim($author_id));
		//Check author name
		if( is_null($author)|| empty($author) )
		{
			$webboardObj->author = " - ";//Default 
		}
		else
		{
			$webboardObj->author = trim($author);
		}
	}
	
	if( empty($errors) )
	{
		if(!$webboardObj->add())
		{
			$errors[] = Tools::displayError('Have some problems. Unable to post.');
		}
		if($back)
		{
			Tools::redirect( Tools::htmlentitiesDecodeUTF8($back) );
		}
	}
	else
	{
		$smarty->assign('errors', $errors);
		displayPostCreator($topic_id.'.1',$post_action );
	}

}

/**
 *
 * @param $page_type - 'board' or 'topic'
 * @param $topic_id - topic id
 * @param $selected_page - selected page number
 * @return unknown_type
 */
function initPagination($page_type, $topic_id, $selected_page)
{
	global $smarty;
	/* constants */
	$num_nearby_page = 2; // if 2, result in 2(nearby)+1(selected)+2(nearby) = 5
	/* Pagination Variables */
	$topic_count_per_page = intval(TOPIC_COUNT_PER_PAGE);
	$total_page_count;
	if( $page_type == POST_ACTION_BOARD)
	{
		$total_page_count = ceil(intval(Webboard::getTotalTopicCount($topic_id))/$topic_count_per_page);
	}
	else if( $page_type == POST_ACTION_TOPIC)
	{
		$total_page_count = ceil(intval(Webboard::getTotalReplyCount($topic_id))/$topic_count_per_page);
	}

	$page_group_start;
	$page_group_end;
	$remote_first_page_visible = true;
	$remote_last_page_visible = true;



	//Set min page in page group
	if($selected_page-$num_nearby_page >= 1 )
	{
		$page_group_start = $selected_page-$num_nearby_page;
	}
	else
	{
		$page_group_start = 1;
	}

	if($selected_page-$num_nearby_page <= 1 )
	{
		$remote_first_page_visible = false;
	}

	//Set max page in page group
	if($selected_page+$num_nearby_page <= $total_page_count )
	{
		$page_group_end = $selected_page+$num_nearby_page;
	}
	else
	{
		$page_group_end = $total_page_count;
	}

	if($selected_page+$num_nearby_page >= $total_page_count )
	{
		$remote_last_page_visible = false;
	}

	$smarty->assign(array(
		'selected_page' => $selected_page,
		'total_page_count' => $total_page_count,
		'page_group_start'=> $page_group_start,
		'page_group_end' => $page_group_end,
		'remote_first_page_visible' => $remote_first_page_visible,
		'remote_last_page_visible' => $remote_last_page_visible,
		'page_type' => strtolower($page_type),
		'topic_id' => $topic_id
	));
}

function validateBoardAndTopicAttributes( $boardOrTopicAttr )
{
	if( 0 == preg_match( REGEX_BOARD_TOPIC, $boardOrTopicAttr ))
	{
		displayBoard("0.1");
	}
	return true;
}
$smarty->assign('errors', $errors);
include(dirname(__FILE__).'/footer.php');

?>